import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import threading
import asyncio
from agents.agent import langgraph_mcp_agent
from agents.class_agent import LangGraphMCPAgent


async def main():
    agent = LangGraphMCPAgent()
    graph = await agent.initialize()
    # graph = await langgraph_mcp_agent()
    current_thread_id = threading.current_thread().ident
    config = {"configurable": {"thread_id": str(current_thread_id)}}
    print("config:", config)

    response_content = []
    while True:
        # 使用异步输入处理
        user_input = await asyncio.to_thread(input, "User: ")
        if user_input.lower() in ["quit", "exit", "q"]:
            print("Goodbye!")
            break
        # 异步处理流更新
        async for event in graph.astream(
            {"messages": [{"role": "user", "content": user_input}]},
            config,
            stream_mode="messages"
        ):
            # print("main:", event)
            # print("\n")
            response_content.append(event[0].content)
    # 查找response_content中最后出现连续5个空字符串的索引
    last_index = -1
    empty_count = 0

    for i, content in enumerate(response_content):
        if content == "":
            empty_count += 1
            if empty_count == 5:
                last_index = i  # 连续5个空字符串的最后一个索引
                empty_count = 0  # 重置计数器继续查找
        else:
            empty_count = 0  # 遇到非空字符串重置计数器

    # 重构response_content为连续5个空字符串的最后一个索引到最后一个字符
    if last_index != -1:
        response_content = response_content[last_index + 1:]

    # 如果重构后为空，返回原始内容
    if not response_content:
        response_content = [""]

    # 将response_content拼接为单个字符串
    full_response = "".join(response_content).strip()

    # 返回清理后的响应
    response_content = [full_response]
    print("mian end response_content:", response_content)
    return response_content


if __name__ == "__main__":
    asyncio.run(main())
